package com.guldan.jaina.manager;

import java.util.ArrayList;
import java.util.List;

import com.guldan.core.constants.CommonConstant;
import com.guldan.core.exception.BusinessException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.dictionary.DictionaryDTO;
import com.guldan.jaina.dto.dictionary.DictionarySearchDTO;
import com.guldan.jaina.utils.DictionaryDomainConvertUtils;
import com.guldan.mapper.db.entity.Dictionary;
import com.guldan.mapper.db.entity.DictionaryExample;
import com.guldan.mapper.db.mapper.DictionaryMapperExt;

/**
 * Created by Silas.
 * Date: 2016/11/7
 * Time: 22:55
 */
@Service
public class DictionaryManager extends BaseManager {

    @Autowired
    private DictionaryMapperExt dictionaryMapperExt;

    //获取单个字典信息
    public DictionaryDTO get(Integer dictionaryId) {
        return DictionaryDomainConvertUtils.convert(dictionaryMapperExt.selectByPrimaryKey(dictionaryId));
    }

    //判断某个字典是否已经存在
    private Boolean checkExist(String dicCode, Integer dicTypeId) {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andDictionaryCodeEqualTo(dicCode);
        criteria.andDicTypeIdEqualTo(dicTypeId);
        criteria.andIsDeleteEqualTo(false);
        int count = dictionaryMapperExt.countByExample(example);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //新增/更新单个字典，传入：DictionaryDTO
    public DictionaryDTO save(DictionaryDTO dto) throws BusinessException {


        Dictionary entity;
        if (dto.getDictionaryId() != null && dto.getDictionaryId() > 0) {

            entity = dictionaryMapperExt.selectByPrimaryKey(dto.getDictionaryId());
            entity.setDictionaryCode(dto.getDictionaryCode());
            entity.setDictionaryName(dto.getDictionaryName());
            entity.setDicTypeId(dto.getDicTypeId());


            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            dictionaryMapperExt.updateByPrimaryKeySelective(entity);
        } else {

            //判断是否存存在
            if (checkExist(dto.getDictionaryCode(), dto.getDicTypeId())) {
                throw new BusinessException("字典Code已存在");
            }
            entity = new Dictionary();
            entity.setDictionaryCode(dto.getDictionaryCode());
            entity.setDictionaryName(dto.getDictionaryName());
            entity.setDicTypeId(dto.getDicTypeId());
            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getModifier());
            entity.setCreateTime(DateUtil.getCurrentTime());
            dictionaryMapperExt.insertSelective(entity);
        }
        dto = DictionaryDomainConvertUtils.convert(entity);
        return dto;
    }

    //删除单个字典信息
    public Boolean delete(Integer dictionaryId) {
        Dictionary entity = dictionaryMapperExt.selectByPrimaryKey(dictionaryId);
        entity.setIsDelete(true);
        return dictionaryMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //分页查询字典信息列表
    public Pagination<DictionaryDTO> list(DictionarySearchDTO dictionarySearchDTO) {
        Pagination<DictionaryDTO> result = new Pagination<DictionaryDTO>(dictionarySearchDTO.getCurrentPage(), dictionarySearchDTO.getPerPage());
        DictionaryExample example = buildSearchExample(dictionarySearchDTO);
        int total = dictionaryMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<DictionaryDTO> data = new ArrayList<DictionaryDTO>();
            List<Dictionary> list = dictionaryMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (Dictionary entity : list) {
                DictionaryDTO dto = DictionaryDomainConvertUtils.convert(entity);
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    //不分页全部查询字典信息列表
    public List<DictionaryDTO> all(DictionarySearchDTO dictionarySearchDTO) {
        DictionaryExample example = buildSearchExample(dictionarySearchDTO);
        List<DictionaryDTO> data = new ArrayList<DictionaryDTO>();
        List<Dictionary> list = dictionaryMapperExt.selectByExample(example);
        for (Dictionary entity : list) {
            DictionaryDTO dto = DictionaryDomainConvertUtils.convert(entity);
            data.add(dto);
        }
        return data;
    }

    //build查询Example
    private DictionaryExample buildSearchExample(DictionarySearchDTO search) {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(search.getDictionaryCode())) {
            criteria.andDictionaryCodeEqualTo(search.getDictionaryCode());
        }
        if (StringUtils.isNotBlank(search.getDictionaryName())) {
            criteria.andDictionaryNameEqualTo(search.getDictionaryName());
        }
        if (search.getDictionaryId() != null && search.getDictionaryId() > 0) {
            criteria.andDictionaryIdEqualTo(search.getDictionaryId());
        }
        if (search.getDicTypeId() != null && search.getDicTypeId() > 0) {
            criteria.andDicTypeIdEqualTo(search.getDicTypeId());
        }
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("dictionary_id asc");
        }
        return example;
    }

    //通过字典类型id+字典code获取字典DTO
    public DictionaryDTO getDicByCodeAndTypeId(String code, Integer typeId) {
        DictionaryDTO dto = new DictionaryDTO();
        if (StringUtils.isNotBlank(code)) {
            try {
                dto = (DictionaryDTO) cacheService.getCache(String.format(CommonConstant.KEY_DIC, typeId, code));
                logger.info("ssssss " + JSONObject.fromObject(dto).toString());
                if (dto != null) {
                    return dto;
                }
            } catch (Exception ex) {
            }

            DictionaryExample example = new DictionaryExample();
            DictionaryExample.Criteria criteria = example.createCriteria();
            criteria.andDicTypeIdEqualTo(typeId);
            criteria.andDictionaryCodeEqualTo(code);

            List<Dictionary> list = dictionaryMapperExt.selectByExample(example);
            if (list != null && list.size() > 0) {
                dto = DictionaryDomainConvertUtils.convert(list.get(0));
            }
        }
        return dto;
    }

}
